import { formatDate } from '../util/formatDate';
import { perKey, planKey } from '../util/const.config';

// ["id","Name","AgeType","IDType","IDNo","Mobile","Birthday","AirCardNo","Type","Status","OweStatus","Balance","UnitID","UnitNo","Unit","DeptID","Dept","Rule","Sex","Notes",""]
// [0,   1,     2,       3,        4,     5,       6,        7,           8,     9,       10,         11,       12,      13,      14,    15,      16,    17,    18,   19,     20]
// ["id", "名称","年龄类型","证件类型","证件号码","手机","生日","航空公司卡号","类别","状态","授信状态","余额","单位ID","单位No","单位名称","部门ID","部门","政策","性别","备注"];
// [[1956,"张飞","成人","身份证","42145234564564","13900000000","1992-10-19","",0,1,3,100000,10,"001.860001","重庆工行",1,"财务部","1,3,5","男","备注",""],["乘机人2"],["乘机人3"]]
// let id = 0, Name = 1, AgeType = 2, IDType = 3, IDNo = 4, Mobile = 5, Birthday = 6, AirCardNo = 7, Type = 8, Status = 9, OweStatus = 10, Balance = 11, UnitID = 12, UnitNo = 13, Unit = 14, DeptID = 15, Dept = 16, Rule = 17, Sex = 18, Notes = 19;
// let perKey = {'id': 0, 'Name': 1, 'AgeType': 2, 'IDType': 3, 'IDNo': 4, 'Mobile': 5, 'Birthday': 6, 'AirCardNo': 7, 'Type': 8, 'Status': 9, 'OweStatus': 10, 'Balance': 11, 'UnitID': 12, 'UnitNo': 13, 'Unit': 14, 'DeptID': 15, 'Dept': 16, 'Rule': 17, 'Sex': 18, 'Notes': 19};
// ["旅客ID", "开始日期","结束日期","出发地", "到达地", "类型","事由","审批状态"]
// [0,       1,        2,       3,        4,       5,      6,      7]
// let _id = 0, StartDate = 1, EndDate = 2, From = 3, To = 4, _Type = 5, Reason = 6, _Status = 7;
// let planKey = {'id': 0, 'StartDate': 1, 'EndDate': 2, 'From': 3, 'To': 4, 'Type': 5, 'Reason': 6, 'Status': 7};

/*
 * --------- 参数说明 -----------
 * 判断乘客是否可以因公出行，使用企业月结
 * @param data [JSON]（getBookInfo的所有数据）
 * @param pidArr [pid,pid,pid] 选中的乘机人的PID（PS：新增乘机人，检查后是非差旅，就将pid传空字符串''）
 * @param stroke {from: '海口', to: '重庆', goDate: '2017-07-01', backDate: '', roundTrip: 1, tickitType: 0} （出发地，目的地，起始时间，返程状态,票的类型）from 起始地，to 到达地，goDate 起始时间，backDate 到达时间，roundTrip（1单程、2往返去程、3往返回程），tickitType（票的类型：0飞机票、1火车票、2汽车票、3船票、4滴滴打车）
 *
 * --------- 返回参数说明 -----------
 * 返回 {status: false, insurance: true, msgCode: true, msg: ''}
 * status true差旅、false非差旅
 * insurance true买保险、false不买保险
 * msgCode true提示、false不提示
 * msg 提示信息
 *
 * --------- 使用方式 -----------
 * let rs = CheckTravelPolicyFun(data, pidArr, stroke);
 * console.log('返回数据', rs);
 * */
window.CheckTravelPolicyFun = (data, pidArr, stroke) => {
  if (!data && pidArr) return;
  data = data instanceof Object ? data : eval('(' + data + ')');
  // console.log('data', data);
  // console.log('pidArr', pidArr);
  // console.log('stroke', stroke);
  /*所有 Passenger*/
  let Passenger = data.Passenger,
    /*指定授信账户的参数*/
    Perm = getPerm(data),
    /*当前用户*/
    currentUser = [],
    /*当前用户Pid*/
    pid,
    /*当前用户Name*/
    name,
    /*当前用户Rule*/
    rule,
    /*当前用户OweStatus*/
    OweStatus = null,
    /*当前用户UnitID*/
    UnitID = null,
    /*当前用户审批状态*/
    is_Approval = null,
    /*授信*/
    travel = [],
    /*非授信*/
    noCredit = [],
    /*非差旅*/
    noTravel = [],
    /*审批通过*/
    approval = [],
    /*未请假*/
    noApply = [],
    /*审批未通过*/
    noApproval = [],
    /*无限制*/
    unlimited = [],
    /*低价*/
    lowPrice = [],
    /*次低价*/
    secondLowPrice = [],
    /*买保险*/
    insurance = [],
    /*不买保险*/
    noInsurance = [],
    /*全部政策*/
    allRule = [];

  for (let j = 0, o = pidArr, oLen = o.length; j < oLen; j++) { /*j*/
    currentUser = [];
    pid = name = rule = '';
    for (let i = 0, r = Passenger, rLen = r.length; i < rLen; i++) {/*i*/
      if (o[j] === '') {/*新增乘机人，非差旅*/
        noTravel.push(currentUser);
      } else if (parseInt(o[j]) === r[i][perKey.id]) { /*id*/

        OweStatus = parseInt(r[i][perKey.OweStatus]);
        UnitID = r[i][perKey.UnitID];
        pid = r[i][perKey.id];
        name = r[i][perKey.Name];
        rule = r[i][perKey.Rule];
        currentUser.push(pid);
        currentUser.push(name);

        // console.log('选中差旅人Rule：', rule);
        if (OweStatus === 2 || (OweStatus === 4 && strfind(Perm, UnitID))) {/*任意账户授信、指定账户授信*/
          travel.push(currentUser);
          /*审批*/
          if (strfind(rule, 11)) {
            is_Approval = isApproval(data, stroke, currentUser, oLen);
            if (is_Approval === 1) {
              approval.push(currentUser);
            } else if (is_Approval === 2) {
              noApply.push(currentUser);
              return { status: false, insurance: true, msgCode: true, msg: gtePromptMsg(currentUser, 'noApply') };
            } else if (is_Approval === 0) {
              noApproval.push(currentUser);
              return { status: false, insurance: true, msgCode: true, msg: gtePromptMsg(currentUser, 'noApproval') };
            }
          }

          /*保险*/
          if (strfind(rule, 10)) {
            noInsurance.push(currentUser);
            if (insurance.length > 0) {
              return { status: false, insurance: true, msgCode: true, msg: gtePromptMsg(currentUser, 'noInsurance') };
            }
          } else {/*买保险*/
            insurance.push(currentUser);
          }

          /********************飞机票********************/
          if (parseInt(stroke.tickitType) === 0) {
            /*政策一致*/
            /* if (strfind(rule, 0) || rule === '') {/!*无限制*!/
             unlimited.push(currentUser);
             if (lowPrice.length > 0 || secondLowPrice.length > 0) {
             return {status: false, insurance: true, msgCode: true, msg: gtePromptMsg(currentUser, 'unlimited')};
             }
             } else*/
            if (strfind(rule, 1)) {/*低价*/
              lowPrice.push(currentUser);
              /*unlimited.length > 0 || */

              if (secondLowPrice.length > 0) {
                return { status: false, insurance: true, msgCode: true, msg: gtePromptMsg(currentUser, 'lowPrice') };
              }
            } else if (strfind(rule, 3)) {/*次低价*/
              secondLowPrice.push(currentUser);
              /*unlimited.length > 0 ||*/
              if (lowPrice.length > 0) {
                return { status: false, insurance: true, msgCode: true, msg: gtePromptMsg(currentUser, 'secondLowPrice') };
              }
            }
          }
          /********************火车票********************/
          else if (parseInt(stroke.tickitType) === 1) {
          }
        } else if (OweStatus === 4 && !strfind(Perm, UnitID)) {/*不是指定账户授信*/
          noCredit.push(currentUser);
          if (oLen > 1) {
            return { status: false, insurance: true, msgCode: true, msg: gtePromptMsg(currentUser, 'noCredit') };
          } else {
            return { status: false, insurance: true, msgCode: false, msg: '' };
          }
        } else {/*非差旅*/
          noTravel.push(currentUser);
          /*if (oLen > 1 && (travel.length > 0 || noCredit.length > 0)) {
           return {status: false, insurance: true, msgCode: true, msg: gtePromptMsg(currentUser, 'noTravel')};
           } else {
           return {status: false, insurance: true, msgCode: false, msg: ''};
           }*/
        }
      }
      else {/*非差旅*/
        pid = r[i][perKey.id];
        name = r[i][perKey.Name];
        currentUser.push(pid);
        currentUser.push(name);
        noTravel.push(currentUser);
      }
      /*id*/
    }
    /*i*/
  }
  /*j*/
  if (pidArr.length === 1 && noTravel.length > 0 && travel.length <= 0) {
    return { status: false, insurance: true, msgCode: false, msg: '' };
  }
  if (pidArr.length > 1 && noTravel.length > 0 && travel.length > 0) {
    return { status: false, insurance: true, msgCode: true, msg: gtePromptMsg(noTravel[0], 'noTravel') };
  } else if (pidArr.length > 1 && noTravel.length > 0 && travel.length <= 0) {
    return { status: false, insurance: true, msgCode: false, msg: '' };
  }

  // return isPolicy(unlimited, lowPrice, secondLowPrice, insurance);
  return { status: true, insurance: false, msgCode: false, msg: '' };
};

/*查找字符串*/
function strfind(str, val) {
  if (!str, !val) return;
  if (str instanceof Array) str.join(',');
  return new RegExp(',' + val + ',').test(',' + str + ',');
}
/*获得单位（UnitID）*/
function getPerm(data) {
  if (!data) return;
  let r = data.Perm;
  // r = [[5488, 84, 0, 45], [5488, 84, 0, 8]];
  let rc = [];
  let UnitID = 1;
  for (let i = 0, len = r.length; i < len; i++) {
    rc.push(r[i][UnitID]);
  }
  return rc;
}

/*
 * 判断审批
 * 1 通过 、0 未通过 、2 未请假
 * @param 参数：所有的数据，航班信息，是否返程，当前用户
 * */
function isApproval(data, stroke, currentUser, currentNum) {
  if (!data && !stroke && !currentUser) return false;
  data = data.Plan || [];
  /*未请假*/
  if (data.length <= 0) {
    if (currentNum > 1) {
      return 0;
    } else {
      return 2;
    }
  }
  /*审批通过*/
  let approval = [],
    /*未请假*/
    noApply = [],
    /*审批未通过*/
    noApproval = [];

  // debugger;
  // let strokeInfo = {from: '北京', to: '重庆', goDate: '2017-07-16', backDate: '2017-07-16', roundTrip: 1, tickitType: 0};

  // 票据信息
  let goDate = stroke.goDate ? formatDate('yyyy-MM-dd', stroke.goDate) : '',
    backDate = stroke.backDate ? formatDate('yyyy-MM-dd', stroke.backDate) : '',
    backFrom, /*返程的去*/
    backTo, /*返程的回*/
    strokeFrom = backTo = stroke.from || '',
    strokeTo = backFrom = stroke.to || '',
    roundTrip = stroke.roundTrip || 1;

  // 审批信息
  let startDate = null,
    endDate = null,
    from = null,
    to = null,
    status = null;

  // let planKey = {'id': 0, 'StartDate': 1, 'EndDate': 2, 'From': 3, 'To': 4, 'Type': 5, 'Reason': 6, 'Status': 7};
  for (let i = 0, r = data, len = r.length; i < len; i++) {

    if (parseInt(currentUser[0]) === r[i][planKey.id]) {
      startDate = r[i][planKey.StartDate] ? formatDate('yyyy-MM-dd', r[i][planKey.StartDate]) : '';
      endDate = r[i][planKey.EndDate] ? formatDate('yyyy-MM-dd', r[i][planKey.EndDate]) : '';
      status = parseInt(r[i][planKey.Status]);
      from = r[i][planKey.From];
      if (from.indexOf('，') > -1) {
        from = from.replace(/，/g, ',')
      }
      to = r[i][planKey.To];
      if (to.indexOf('，') > -1) {
        to = to.replace(/，/g, ',')
      }
      // console.log('循环中的from:', from);
      // console.log('循环中的to:', to);

      // 时间 地址 状态 都满足
      /*返*/
      if (backDate) {
        /*去和回*/
        if (
          (goDate >= startDate && goDate <= endDate && (strfind(strokeFrom, from) || strfind(to, strokeFrom)) && strfind(to, strokeTo) && status === 2)
          &&
          (backDate >= startDate && backDate <= endDate && strfind(to, backFrom) && (strfind(backTo, from) || strfind(to, backTo)) && status === 2)
        ) { /*单程*/
          approval.push(r[i]);
        } else {
          noApproval.push(r[i]);
        }
      } else if (
        (goDate >= startDate && goDate <= endDate && (strfind(strokeFrom, from) || strfind(to, strokeFrom)) && strfind(to, strokeTo) && status === 2)
        ||
        (goDate >= startDate && goDate <= endDate && strfind(backFrom, from) && strfind(to, backTo) && status === 2)
      ) { /*单程*/
        approval.push(r[i]);
      }
      /*roundTrip*/
    }
    /*id*/
  }
  /*i*/
  /*  console.log('approval', approval);
   console.log('noApproval', noApproval);
   console.log('noApply', noApply);*/
  if (approval.length <= 0 && noApproval.length <= 0) {/*未请假*/
    return 2;
  }

  if (approval.length <= 0 && noApproval.length > 0) {/*未通过*/
    return 0;
  }

  return 1;
}

/*获得提示信息*/
function gtePromptMsg(arr, key) {
  if (!arr && !key) return;
  let rc = `尊敬的旅客：`;

  if (key === 'noTravel') {
    if (arr.length <= 0) {
      rc += `新增的乘机人不是差旅用户，一起下单不能使用企业月结，如需月结请分开下单`;
    } else {
      rc += `${arr[1]} 是非差旅用户，并未开通企业月结，如需月结请分开下单`;
    }
  } else if (key === 'noCredit') {
    rc += `${arr[1]} 不是指定授信（企业月结）的账户，如需月结请分开下单`;
  } else if (key === 'noApproval') {
    rc += `${arr[1]} 并未通过出差审批，暂时不能使用企业月结，如需月结请分开下单`;
  } else if (key === 'noApply') {
    rc += `${arr[1]} 并未请假出行，暂时不能使用企业月结，请提交申请后在下单`;
  } else if (key === 'noInsurance') {
    rc += `${arr[1]} 一起预定机票不需要购买保险，差旅政策不一致，暂时不能使用企业月结，如需月结请分开下单`;
  } else if (key === 'unlimited' || key === 'lowPrice' || key === 'secondLowPrice') {
    rc += `${arr[1]} 一起预定机票，差旅政策不一致，暂时不能使用企业月结，如需月结请分开下单`;
  }

  rc += `，或者自费出行。`;

  return rc;
}